package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WaitNotifyPrintABCService {

    private final Object lock = new Object();
    private int state = 0; // 0 表示 A, 1 表示 B, 2 表示 C
    private static final int TOTAL_CYCLES = 5; // 总循环次数

    public void printABCSequence() {
        Thread threadA = new Thread(this::printA);
        Thread threadB = new Thread(this::printB);
        Thread threadC = new Thread(this::printC);

        threadA.start();
        threadB.start();
        threadC.start();

        try {
            threadA.join();
            threadB.join();
            threadC.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("主线程被中断", e);
        }

        log.info("所有循环已完成，任务结束");
    }

    private void printA() {
        for (int cycle = 0; cycle < TOTAL_CYCLES; cycle++) {
            synchronized (lock) {
                while (state != 0) {
                    try {
                        lock.wait(); // 等待A的执行条件
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        log.error("线程A被中断", e);
                    }
                }
                for (int i = 0; i < 3; i++) {
                    log.info("A");
                }
                state = 1; // 切换到B
                lock.notifyAll(); // 唤醒B线程
            }
        }
    }

    private void printB() {
        for (int cycle = 0; cycle < TOTAL_CYCLES; cycle++) {
            synchronized (lock) {
                while (state != 1) {
                    try {
                        lock.wait(); // 等待B的执行条件
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        log.error("线程B被中断", e);
                    }
                }
                for (int i = 0; i < 2; i++) {
                    log.info("B");
                }
                state = 2; // 切换到C
                lock.notifyAll(); // 唤醒C线程
            }
        }
    }

    private void printC() {
        for (int cycle = 0; cycle < TOTAL_CYCLES; cycle++) {
            synchronized (lock) {
                while (state != 2) {
                    try {
                        lock.wait(); // 等待C的执行条件
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        log.error("线程C被中断", e);
                    }
                }
                log.info("C");
                state = 0; // 重置为A的状态
                lock.notifyAll(); // 唤醒A线程
            }
        }
    }
}
